<?php
namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\Setup;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

class SetupController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->Setup = new Setup();
    }
    //访客类型查询列表
    public function setTypeList($id){
        $cmpId = $id;
        if(empty($cmpId)){
            return response()->json(['code'=>400,'msg'=>'公司不存在','data'=>'']);
        }else{
            $data =  DB::table('visitorType')
                ->where('cmpId', '=',$cmpId)
                ->select(['id','cmpId','typeName','status','type'])
                ->get();
            if(empty($data)){
                return response()->json(['code'=>400,'msg'=>'公司不存在','data'=>'']);
            }else{
                return response()->json(['code'=>200,'msg'=>'请求成功','data'=>$data]);
            }
        }
    }
    //类型设置提交
    public function setTypeSet(Request $request){
        $data = $request->all();
        if(empty($data)){
            return response()->json(['code'=>400,'msg'=>"修改失败",'data'=>'']);
        }
        $g=0;
        $h = count($data['data']);
        foreach($data['data'] as $k=>$v){
            $result =   DB::table('visitorType')
                ->where('id', $v['id'])
                ->update(['status' => $v['status']]);
            if($result){
                $g++;
            }
        }
        if($g == $h){
            return response()->json(['code'=>200,'msg'=>"修改成功",'data'=>'']);
        }else{
            return response()->json(['code'=>400,'msg'=>"修改失败",'data'=>'']);
        }
    }
    //访客类型字段获取
    public function setInfoIpad($id){
        $typeId = $id;
        if(empty($typeId)){
            return response()->json(['code'=>400,'msg'=>"访客信息不存在",'data'=>'']);
        }
        $data =  DB::table('visitorTypeSet')
            ->where([['visitorTypeId',$typeId],['isHidden','=',1],['typeSign','!=',100]])
            ->orWhere([['visitorTypeId',$typeId],['typeSign',1]])
            ->select(['id','typeName','isHidden','isRequired','type'])
            ->get();
        $others = DB::table('visitorTypeSet')
            ->where([['visitorTypeId',$typeId],['isHidden','=',1],['typeSign','=',100]])
            ->select(['id','typeName','isHidden','isRequired','type','option as item'])
            ->get();
        foreach($data as $k=>$v){
            if($v->typeName == '拍照'){
                $photo = $v;
            }else{
                $date[] = $v;
            }
        }
        if(empty($photo)){
            $photo = "";
        }
        if(empty($date)){
            $date = "";
        }
        foreach($others as $k=>$v){
                $others[$k]->item = json_decode($v->item,true);
        }
        if(empty($data)){
            return response()->json(['code'=>400,'msg'=>'访客信息不存在','data'=>'']);
        }else{
            return response()->json(['code'=>200,'msg'=>'请求成功','data'=>['info'=>$date,'others'=>$others,'id'=>$typeId,'photo'=>$photo],]);
        }
    }
    //信息设置加载
    public function setInfoList($id){
        $typeId = $id;
        if(empty($typeId)){
            return response()->json(['code'=>400,'msg'=>"访客信息不存在",'data'=>'']);
        }
        $cmpId = DB::table('visitorType')
            ->where('id', '=',$typeId)
            ->select(['id','cmpId'])
            ->first();
        if(empty($cmpId)){
            return response()->json(['code'=>400,'msg'=>'访客信息不存在','data'=>'']);
        }
        $data =  DB::table('visitorTypeSet')
            ->where([['visitorTypeId',$typeId],['typeSign','!=',100]])
            ->select(['id','typeName','isHidden','isRequired','option as item','type','typeSign'])
            ->get();
        $others = DB::table('visitorTypeSet')
            ->where([['visitorTypeId',$typeId],['typeSign','=',100]])
            ->select(['id','typeName','isHidden','isRequired','option as item','type','typeSign'])
            ->get();
        foreach($others as $k=>$v){
           if($v->type == 1){
               $v->item = json_decode($v->item,true);
           }
        }
        $wifi = DB::table('cmpWifi')
            ->where('cmpId', '=',$cmpId->cmpId)
            ->select(['id','userName','passWord'])
            ->first();
        if(empty($wifi)){
            $wifi = ['id'=>'','userName'=>'','passWord'=>''];
        }
        if(empty($data)){
            return response()->json(['code'=>400,'msg'=>'访客信息不存在','data'=>'']);
        }else{
            return response()->json(['code'=>200,'msg'=>'请求成功','data'=>['default'=>$data,'id'=> $typeId,'custom'=>$others,'wifi'=>$wifi]]);
        }
    }
//    自定义删除
    public function setDel(Request $request){
       
        $id = $request->input('id');
        if(!empty($id)){
            $result = DB::table('visitorTypeSet')->where('id',$id)->delete();
            if(!empty($result)){
                return response()->json(['code'=>200,'msg'=>"删除成功",'data'=>'']);
            }else{
                return response()->json(['code'=>400,'msg'=>"删除失败",'data'=>'']);
            }
        }else{
            return response()->json(['code'=>400,'msg'=>"删除失败",'data'=>'']);
        }
    }
    //信息设置修改
    public function setInfoSave(Request $request){
        $data = $request->all();
       if(empty($data)){
           return response()->json(['code'=>400,'msg'=>"修改失败",'data'=>'']);
       }
       $id = $request->input('id');
       $info = DB::table('visitorType')->where('id',$id)->first();
        DB::beginTransaction();
        try{
            foreach($request->input('default') as $k=>$v){
                  DB::table('visitorTypeSet')
                    ->where('id', $v['id'])
                    ->update(['isHidden' => $v['isHidden'],'isRequired'=>$v['isRequired']]);
            }
            $custom = $request->input('custom');
            if($custom != '[]'){
                foreach($request->input('custom') as $k=>$v){
                    if(!empty($v['id'])){
                        $result = DB::table('visitorTypeSet')->where([['typeName',$v['typeName']],['visitorTypeId',$id],['id','!=',$v['id']]])->first();
                    }else{
                        $result = DB::table('visitorTypeSet')->where(['typeName'=>$v['typeName'],'visitorTypeId'=>$id])->first();
                    }
                    if(!empty($result)){
                        DB::rollback();
                        return  response()->json(['code'=>400,'msg'=>'自定义字段重复','data'=>'']);
                    }
                    if($v['type'] == 0){
                        if(empty($v['id'])){
                            DB::table('visitorTypeSet')->insert(
                                ['cmpId' => $info->cmpId, 'visitorTypeId' =>$id,'typeName' => $v['typeName'],'isHidden'=>$v['isHidden'],'type'=>$v['type'],'isRequired'=>$v['isRequired'],'typeSign'=>100]);
                        }else{
                            DB::table('visitorTypeSet')
                                ->where('id', $v['id'])
                                ->update(['typeName' => $v['typeName'],'isHidden'=>$v['isHidden'],'isRequired'=>$v['isRequired']]);
                        }
                       
                    }else{
                        if(empty($v['id'])){
                        DB::table('visitorTypeSet')->insert(
                            ['cmpId' => $info->cmpId, 'visitorTypeId' =>$id,'typeName' => $v['typeName'],'isHidden'=>$v['isHidden'],'type'=>$v['type'],'option'=>json_encode($v['item']),'isRequired'=>$v['isRequired'],'typeSign'=>100]);
                    }else{
                            DB::table('visitorTypeSet')
                                ->where('id', $v['id'])
                                ->update(['typeName' => $v['typeName'],'isHidden'=>$v['isHidden'],'isRequired'=>$v['isRequired'],'option'=>json_encode($v['item'])]);
                        }
                    }
                }
            }
            DB::commit();
        }catch(\Exception $e ){
            DB::rollback();
            return  response()->json(['code'=>400,'msg'=>'修改失败','data'=>'']);
        }
        return response()->json(['code'=>200,'msg'=>"修改成功",'data'=>'']);
    }
    //便签信息查询
    public function momeInfo(Request $request){
        $data = $request->all();
        if(empty($data)){
            return response()->json(['code'=>400,'msg'=>'访客信息不存在','data'=>'']);
        }
        $mome =   DB::table('visitorInfo')->where([
                            ['cmpId', '=', $data['cmpId']],
                            ['type', '=', $data['type']],
                            ])->get()->toArray();
        $wifi = DB::table('cmpWifi')
            ->where('cmpId', '=',$data['cmpId'])
            ->select(['id','cmpId','userName','passWord'])
            ->get()->toArray();
        $note  = DB::table('cmpInfo')->where('id',$data['cmpId'])->first();
        if(empty($wifi)){
            $wifi = ['id'=>'','cmpId'=>$data['cmpId'],'userName'=>'','passWord'=>''];
        }
        return response()->json(['code'=>200,'msg'=>'请求成功','data'=>$mome,'wifi'=>$wifi,'from'=>2,'noteSign'=>$note->momeType]);
    }
    //便签信息保存
    public  function setMome(Request $request){
        $data = json_decode($request->input('data'),true);
        $wifi = json_decode($request->input('wifi'),true);
        $time = time();
        if(empty($wifi)){
            return response()->json(['code'=>400,'msg'=>"便签设置失败"]);
        }
        try {
                foreach($data as $k=>$v){
                    DB::table('visitorInfo')
                        ->where('id', $v['id'])
                        ->update(['isHidden' => $v['isHidden']]);
                }
            $cmpId = $wifi['cmpId'];
            $name = $wifi['userName'];
            $pass = $wifi['passWord'];
            $momeType = $request->input('noteSign') ?? 1;
            DB::table('cmpInfo')->where(['id'=>$cmpId])->update(['momeType'=>$momeType,'updatedAt'=>$time]);
            $oldWifi = DB::table('cmpWifi')
                ->where('cmpId', '=',$cmpId)
                ->select(['id','cmpId','userName','passWord'])
                ->get()->toArray();
            if(empty($oldWifi)){
                if(!empty($pass) || !empty($name)){
                    DB::table('cmpWifi')->insert(
                        ['cmpId' =>$wifi['cmpId'], 'typeName'=>'wifi','userName'=>$wifi['userName'], 'passWord'=>$wifi['passWord']]
                    );
                }
            }else{
                $id = $wifi['id'];
                if(empty($id)){
                    return response()->json(['code'=>400,'msg'=>'便签设置失败','data'=>'']);
                }
                DB::table('cmpWifi')->where('id',$wifi['id'])->update(['typeName'=>'wifi','userName'=>$wifi['userName'], 'passWord'=>$wifi['passWord']]);
            }
        } catch (\Exception $e) {
            return response()->json(['code'=>400,'msg'=>'便签设置失败','data'=>'']);
        }
            return response()->json(['code'=>200,'msg'=>'便签设置成功','data'=>'']);
    }
//    修改密码
    public function changePW(Request $request){
        $data = $request->all();
        if(empty($data)){
            return response()->json(['code'=>400,'msg'=>'密码修改失败','data'=>'']);
        }
        $mobile = $data['mobile'];
       
        if($data['newPW'] != $data['reNewPW']){
            return response()->json(['code'=>400,'msg'=>'新密码与确认密码不一致','data'=>'']);
        }
        $userInfo = DB::table('userAdm')
            ->where('mobile', '=',$data['mobile'])
            ->select(['id','passWord','salt'])
            ->first();
            
        if(empty($userInfo)){
            return response()->json(['code'=>400,'msg'=>'密码修改失败','data'=>'']);
        }
        if($data['type'] == 1){
            $pwd = md5($data['oldPW'].$userInfo->salt);
            $newPW = md5($data['newPW'].$userInfo->salt);
            if($pwd != $userInfo->passWord){
                return response()->json(['code'=>400,'msg'=>'旧密码错误','data'=>'']);
            }
        }elseif($data['type'] == 2){
            $code = $data['info'];
            $redCode = Redis::get($mobile.'info');
            $redTime = Redis::get($mobile.'infoTime');
            $time = time();
            $timeApart = $time -$redTime;
            if($timeApart < 0 || $timeApart > 300 || ($redCode != $code))
            {
                return response()->json(['code'=>400,'msg'=>'验证码错误或失效','data'=>'']);
            }
            $newPW = md5($data['newPW'].$userInfo->salt);
        }
        $validity = time()+7*24*3600;
        $result = DB::table('userAdm')->where('id',$userInfo->id)->update(['passWord'=>$newPW,'validity'=>$validity]);
        DB::table('multiDeviceLogin')->where('uid', '=', $userInfo->id)->delete();
        if($result){
            return response()->json(['code'=>200,'msg'=>'密码修改成功','data'=>'']);
        }else{
            return response()->json(['code'=>400,'msg'=>'密码修改失败','data'=>'']);
        }
    }
//    发送验证码
    public function sendMessage(Request $request){
        $mobile = $request->input('mobile');
//        $mobile = $id;
        if(empty($mobile)){
            return  response()->json(['code'=>400,'msg'=>'请输入手机号','data'=>'']);
        }
        if(empty($mobile) || strlen($mobile)!=11){
            return  response()->json(['code'=>400,'msg'=>'手机号错误','data'=>'']);
        }
        $mobileExpire = Redis::exists($mobile);
        if($mobileExpire)  return  response()->json(['code'=>400,'msg'=>'验证码已发送','data'=>'']);
        $config = Config::get('info.message_config');
        $easySms = new EasySms($config);
        $code = rand(1000,9999);
        $redMobile = Redis::exists($mobile.'code');
        if($redMobile){
            $redCode = Redis::get($mobile.'code');
            Redis::del($mobile.'code');
        }
        $redTime = Redis::exists($mobile.'time');
        if($redTime){
            $redTime = Redis::get($mobile.'time');
            Redis::del($mobile.'time');
        }
        try{
            $result=$easySms->send($mobile, [
                'content' => '您的验证码${code}，该验证码5分钟内有效，请勿泄漏于他人！',
                'template' => 'SMS_126570108',
                'data' => [
                    'code' => $code,
                ],
            ]);
        }catch(NoGatewayAvailableException $e){
            return  response()->json(['code'=>200,'msg'=>'由于您操作次数过多，5分钟后再进行操作','data'=>'']);
        }
        Redis::setex($mobile.'code', 300, $code);
        Redis::setex($mobile.'time', 300, time());
        Redis::setex($mobile, 60,$mobile);
        if($result['aliyun']['status']=='success'){
            return  response()->json(['code'=>200,'msg'=>'短信发送成功','data'=>'']);
        }else{
            return  response()->json(['code'=>200,'msg'=>'由于您操作次数过多，5分钟后再进行操作','data'=>'']);
        }
    }
//    验证验证码
    public function verifyMessage(Request $request){
        $data = $request->all();
        if(empty($data)){
            return  response()->json(['code'=>400,'msg'=>'验证失败','data'=>'']);
        }
        $mobile = $data['mobile'];
        $postMessage = $data['code'];
       if($data['type']==2){
           $mobile = $data['newMobile'];
       }
        $nowTime = time();
        $redisMessage  = Redis::get($mobile.'code');
        $redisTime = Redis::get($mobile.'time');
        $timeApart = $nowTime - $redisTime;
        if($timeApart < 0 || $timeApart > 300 || ($redisMessage != $postMessage))
        {
            return response()->json(['code'=>400,'msg'=>'验证码错误或失效','data'=>'']);
        }
        if($data['type']==1){
            $info = str_random(20);
            $redMobile = Redis::exists($mobile.'info');
            if($redMobile){
                Redis::del($mobile.'info');
            }
            $redTime = Redis::exists($mobile.'infoTime');
            if($redTime){
                Redis::del($mobile.'infoTime');
            }
            Redis::setex($mobile.'info', 300, $info);
            Redis::setex($mobile.'infoTime', 300, time());
            return response()->json(['code'=>200,'msg'=>'验证成功','data'=>['info'=>$info]]);
        }elseif($data['type']==2){
            $result = DB::table('userAdm')->where('mobile',$data['newMobile'])->first();
            if(!empty($result)){
                return  response()->json(['code'=>400,'msg'=>'手机号已被注册','data'=>'']);
            }
            $oldMobile = $data['mobile'];
            $newMobile = $data['newMobile'];
            $result = DB::table('userAdm')->where('mobile',$oldMobile)->update(['mobile'=>$newMobile]);
            if($result){
                return response()->json(['code'=>200,'msg'=>'手机号修改成功','data'=>['info'=>'']]);
            }else{
                return response()->json(['code'=>400,'msg'=>'手机号修改失败','data'=>['info'=>'']]);
            }
        }
    }
//    Ipad进入设置时验证
    public function verifyPW(Request $request){
        $token = $request->input('authtoken');
        $pwd = $request->input('pwd');
        if(empty($pwd)){
            return response()->json(['code'=>400,'msg'=>'请重新输入密码','data'=>'']);
        }
        $info = DB::table('multiDeviceLogin')
            ->leftJoin('userAdm', 'multiDeviceLogin.uid', '=', 'userAdm.id')
            ->where('multiDeviceLogin.token','=',$token)
            ->first();
        if(empty($info)){
            return response()->json(['code'=>400,'msg'=>'未登录','data'=>'']);
        }
        $fromPwd = md5($pwd.$info->salt);
        if($fromPwd == $info->passWord){
            return response()->json(['code'=>200,'msg'=>'密码正确','data'=>'']);
        }else{
            return response()->json(['code'=>400,'msg'=>'密码错误','data'=>'']);
        }
    }
}
